var RegionGridPanel = function() {
	var validator;
	return {
		init : function() {
			var tableId="region_grid_panel";
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';
			
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "regionCode",
					"value" : $("#regionCode").val().trim()
				});
				aoData.push({
					"name" : "regionName",
					"value" : $("#regionName").val().trim()
				});
				aoData.push({
					"name" : "regionType",
					"value" : $("#regionType").val()
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"jsonData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
			
			$('#region_grid_panel').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/region/findEntityPageByQuery.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [
						{
							"data" : "pkId",
							"render" : function(data, type, full, meta) {
								 return checkBoxDivStr;
							},
							"bSortable" : false
						},
						util.createRowIndex(),
						{
							"data" : "regionCode",
							"bSortable" : false,
						    "defaultContent": ""
						},
						{
							"data" : "regionName",
							"bSortable" : false,
						    "defaultContent": ""
						},
						{
							"data" : "regionTypeName",
							"bSortable" : false,
						    "defaultContent": ""
						}, 
						{
							"data" : "parentRegionName",
							"bSortable" : false,
							"defaultContent": ""
						}],
						"fnDrawCallback" : function(oSetting) {
							util.clearSelected(tableId);
						}
			});

			util.getDictByParentKey("QYLXDM", 'regionType', '请选择');
			
			$('#region_grid_panel tbody').on('click', 'tr', function() {
				var table = $('#region_grid_panel').DataTable();
				if ($(this).hasClass('selected')) {
					$(this).removeClass('selected');
				} else {
					table.$('tr.selected').removeClass('selected');
					$(this).addClass('selected');
				}
			});
			
			jQuery('#region_grid_panel .group-checkable').change(function() {
				var set = jQuery(this).attr("data-set");
				var checked = jQuery(this).is(":checked");
				jQuery(set).each(function() {
					if (checked) {
						$($(this).parent()).attr("class", "checked");
					} else {
						$($(this).parent()).removeClass("checked");
					}
				});
				jQuery.uniform.update(set);
			});
			
			//查询
			$("#btn_query").click(function(e) {
				var table = $('#region_grid_panel').DataTable();
				table.draw(true);
			});
			
			// 重置
			$("#btn_reset").on("click", function(e) {
				$("#regionCode").val("");
				$("#regionName").val("");
				$("#regionType").val("");
			});
			
			//删除区域
			$("#region_table_del").on("click",function(e) {
				var d = [];
				d = util.getCheckedData("region_grid_panel");
				if (d.length == 0) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return;
				} else {
					util.showModal("#_confirmModal", "您确定要删除选中的记录及子记录？", "_confirmModal_yes");
				}
			});
			
			//确认删除
			$("#_confirmModal").on('click', '#_confirmModal_yes', function() {
				var d = [];
				d = util.getCheckedData("region_grid_panel");
				var idArray=[];
				for (var i=0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				var table = $('#region_grid_panel').DataTable();
				var selRows = table.rows('.selected');
				var selData = selRows.data();
				$.ajax({
					"type" : "post",
					"url" : "main/region/delRegion.mvc",
					"dataType" : "json",
					"data" : {
						"pkId" : idArray.join(",")
					},
					"success" : function(resp) {
						selRows.remove();
						table.draw(true);
						rmsBox.notify('success', {msg: '删除成功！'});
					},  
		            error: function (msg) {  
		            	rmsBox.notify('error', {msg: '删除失败！', delay: 3000});
		            } 
				});
			})
			
			//关闭弹窗清空表单内容
			$("#form_btn_close").click(function(){
				$("#form_id").val("");
				$("#add_parentRegion").attr("value", "");
				$("#add_parentRegionName").attr("value", "");
				$("#region_form")[0].reset();
				if (validator) {
					validator.resetForm();
				}
			});
			
			// 新增区域
			$("#region_table_new").on("click", function(e) {
				$('#addRegion_title').text('新增区域');
				createTree();
				util.getDictByParentKey("QYLXDM", 'add_regionType', '请选择');
				$("#add_region").modal({show:true, keyboard:false});
			});
			
			// 修改
			$("#region_table_edit").on("click",function(e) {
				$('#addRegion_title').text('编辑区域');
				var d = [];
				d = util.getCheckedData("region_grid_panel");
				if (d.length != 1) {
					util.showModal("#_alertModal", "请选择一条记录进行操作！");
					return;
				}
				$.ajax({
					"type" : "post",
					"url" : "main/region/initEditRegionById.mvc",
					"dataType" : "json",
					"data" : {id:d[0].pkId},
					"success" : function(data) {
						var region = data.region;
						util.createOption("add_regionType", "请选择", data.regionTypeDict)
						$("#form_id").val(region.pkId);
						$("#add_regionName").val(region.regionName);
						$("#add_regionCode").val(region.regionCode);
						$("#add_regionType").val(region.regionType);
						//创建树
						var zNodes = data.regTree;  
		                $.fn.zTree.init($("#regionTreeDemo"), setting, zNodes);
						//给树赋值
						if (region.parentRegion) {
							var treeObj = $.fn.zTree.getZTreeObj("regionTreeDemo");
						    var node=treeObj.getNodeByParam("pkId",region.parentRegion, null);
					    	treeObj.selectNode(node,false);
						    $("#add_parentRegionName").attr("value", node.regionName);  
					        $("#add_parentRegion").attr("value", node.pkId);
						}
						$("#add_region").modal({show:true, keyboard:false});
					}
				});
			});
			
			// 新增区域 保存
			$("#form_region_save").click(function(e) {
				validator = validateMyForm("region_form");
				if(validator.form()){
					save();
				}else{
					return false;
				}
				
			});
			
			
			//保存方法
			function save() {
				var d = {};
				var id = $("#form_id").val();
				var parentRegion = $("#add_parentRegion").val() == null || $("#add_parentRegion").val().length == 0 ? '' : $("#add_parentRegion").val();
				var regionCode = $("#add_regionCode").val();
				var regionName = $("#add_regionName").val();
				var regionType = $("#add_regionType").val();
				
				d['parentRegion'] = parentRegion;
				d['regionCode'] = regionCode;
				d['regionName'] = regionName;
				d['regionType'] = regionType;
				d['id'] = id;
				var table = $('#region_grid_panel').DataTable();
				$.ajax({
					"type" : "post",
					"url" : "main/region/saveOrUpdateRegion.mvc",
					"dataType" : "json",
					"data" : {
						"record" : JSON.stringify(d)
					},
					"success" : function(resp) {
						if (resp.msg == 'parentRegion_error') {
							rmsBox.notify('error', {msg: '上级行政区域不能是当前区域的子区域！', delay: 3000, width: 380});
							return;
						} else if (resp.msg == 'error') {
							rmsBox.notify('error', {msg: '操作失败！',delay: 3000});
							return;
						} else if (resp.msg == 'duplicate') {
							rmsBox.notify('error', {msg: '区域名称或区域编码已存在！', delay: 3000, width: 320});
							return;
						} 
						rmsBox.notify('success', {msg: '操作成功！'});
						$("#form_btn_close").click();
						table.draw(true);
					}
				});
			};
			
			//validate 自定义验证
			function validateMyForm(formId){
				return $( '#' + formId ).validate({  
					errorElement: 'em',
					focusInvalid: false, 
					ignore: "",
			        rules:{  
			        	add_regionCode:'required',
			        	add_regionName:'required',
			        	add_regionType:'required'
			            },  
			        messages:{  
			        	add_regionCode:'不能为空',
			        	add_regionName:'不能为空',
			        	add_regionType:'不能为空'
			            }, 
			            errorPlacement: function (error, element) { 
			            	//默认以span形式显示在输入框后
		                   error.insertAfter(element);
		                   $(element.next()).attr('title', $(error).text()).tooltip();
		                   $(error).text('');
		                }
			    });  
			};
			
			
			$(function(){
				$('.search-body input').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('.search-button #btn_query').click();
					}
				});
			});
		}
	};
}();

/******************区域树 regionTree 开始******************************/
function showMenu() {  
    var nameObj = $("#add_parentRegionName");  
    var nameOffset = $("#add_parentRegionName").offset(); 
    //计算 没计算好
    $("#regionContent").css({ left: 122 + "px", top: 27 + "px" }).slideDown("fast");  

    $("body").bind("mousedown", onBodyDown);  
} 

var setting = {  
    view: {  
        showLine: false,  
        dblClickExpand: true  
    },  
    data: {  
        key : {
            name: "regionName"
        },
        simpleData: {
            enable: true,  
            idKey: "pkId",  
            pIdKey: "parentRegion",  
            rootPId: "0"
        }  
    },  
    callback: {  
        beforeClick: beforeClick,  
        onClick: onClick  
    }  
};  

function createTree() {  
    var zNodes;  
    $.ajax({  
        type: 'POST',  
        url: "main/region/getRegionTree.mvc", //url    
        data: { id: "0" },  
        dataType: "json",   //可以是text，如果用text，返回的结果为字符串；如果需要json格式的，可是设置为json  
        ContentType: "application/json; charset=utf-8",  
        success: function (data) {  
            zNodes = data.aaData;  
            $.fn.zTree.init($("#regionTreeDemo"), setting, zNodes);  
        },  
        error: function (msg) {  
            console.info('获取树失败');
        }  
    }); 
}  

// 控制父节点不显示图标  
function showIconForTree(treeId, treeNode) {  
    return !treeNode.isParent;  
};  

	
function beforeClick(treeId, treeNode) { 
  	return true;  
}  

function onClick(e, treeId, treeNode) {  
    var zTree = $.fn.zTree.getZTreeObj("regionTreeDemo"),  
    nodes = zTree.getSelectedNodes(); 
    $("#add_parentRegionName").attr("value", nodes[0].regionName);  
    $("#add_parentRegion").attr("value", nodes[0].pkId);
    hideMenu();
}  

function hideMenu() {  
    $("#regionContent").fadeOut("fast");  
    $("body").unbind("mousedown", onBodyDown);  
}  
// 当点击窗口其他区域时zTree消息框隐藏  
function onBodyDown(event) {  
    if (!(event.target.id == "menuBtn" || event.target.id == "regionContent" || $(event.target).parents("#regionContent").length > 0)) {  
        hideMenu();  
    }  
}  
/******************区域树 regionTree 结束******************************/
